//
//  NSSavePanelExtension.swift
//  JKTools
//
//  Created by 姜奎 on 2024/4/23.
//

import Cocoa

extension NSSavePanel {
    static func save(message: String? = nil, name: String? = nil, completion:@escaping (URL?)->Void) {
        save(directoryURL: FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first, message: message, name: name, completion: completion)
    }

    static func save(directoryURL: URL?, message: String? = nil, name: String? = nil, completion:@escaping (URL?)->Void) {


        guard let path = directoryURL?.path() else { return }

        if let bookmarkData = UserDefaults.readBookmarkData(by: directoryURL) {

            _ = bookmarkData.startAccessingSecurityScopedResource()
            completion(bookmarkData)
            bookmarkData.stopAccessingSecurityScopedResource()
            return
        }


        let savePanel = NSSavePanel()
        savePanel.message = message ?? "如果路径不存在，请手动创建[\(path)]。"
        savePanel.showsResizeIndicator = true
        savePanel.showsHiddenFiles = true
        savePanel.canCreateDirectories = true
        savePanel.canSelectHiddenExtension = true
        if let name = name {
            savePanel.nameFieldStringValue = "\(name)"
        }

        savePanel.begin { resp in
            guard resp == .OK else {
                return
            }
            completion(savePanel.url)
        }
    }
}
